package com.qdxwx.manage.controller.manager;

import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.manager.ManagerService;
import com.qdxwx.data.service.manager.PostService;
import com.qdxwx.data.service.manager.RoleService;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.manage.annotation.Log;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.enums.BusinessType;
import com.qdxwx.models.manager.Manager;
import com.qdxwx.models.manager.Post;
import com.qdxwx.models.manager.Role;
import com.qdxwx.models.user.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 编辑用户信息
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/manager")
public class ManagerEditController extends BaseController {

    @Autowired
    private ManagerService managerService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PostService postService;

    /**
     * 新增用户
     */
    @GetMapping("/add.html")
    public String add(ModelMap mmap) {
        mmap.put("roles", roleService.getList(new Role(), null));
        mmap.put("posts", postService.getList(new Post(), null));
        return "manager/manager-add";
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit.html")
    public String edit(HttpServletRequest request, ModelMap mmap) {
        int managerId = TKConvert.toInteger(request.getParameter("id"));
        if (managerId < 1) return error404;
        Manager manager = managerService.get(managerId);
        if (manager == null) return error500;
        mmap.put("manager", manager);
        mmap.put("roles", roleService.getList(new Role(), null));
        mmap.put("posts", postService.getList(new Post(), null));
        mmap.put("roleGroup", managerService.getRoleGroup(managerId));
        mmap.put("postGroup", managerService.getPostGroup(managerId));
        return "manager/manager-edit";
    }

    /**
     * 新增保存用户
     */
    @Log(title = "添加管理员", businessType = BusinessType.INSERT)
    @Permissions("manager:add")
    @PostMapping("/add.json")
    @ResponseBody
    public AjaxResult add(HttpServletRequest request) {
        String managerName = TKString.trim(request.getParameter("managerName"));
        if (TKString.isEmpty(managerName)) return error("请输入用户名");
        String mobile = TKString.trim(request.getParameter("mobile"));
        if (!TKString.isMobile(mobile)) return error("请输入正确的手机号码");
        if (managerService.checkMobile(mobile)) return error("该手机号码已被注册");
        String loginName = TKString.trim(request.getParameter("loginName"));
        if (TKString.isEmpty(loginName)) return error("请输入登录账户");
        if (!TKString.isEnglish(loginName)){
            return error("登录名称只能是字母数字组合");
        }
        loginName = loginName.toLowerCase();
        if (managerService.checkLoginName(loginName)) return error("该登录名称已被使用");
        Integer[] roleIds = TKConvert.toIntArray(request.getParameter("roleIds"));
        if (roleIds.length < 1) return error("请选择角色");
        Integer[] postIds = TKConvert.toIntArray(request.getParameter("postIds"));
        if (postIds.length < 1) return error("请选择岗位");
        Manager manager = new Manager();
        manager.setCompanyId(SessionUtils.getManager().getCompanyId());
        manager.setCreateBy(SessionUtils.getLoginName());
        manager.setLoginPwd(TKConvert.toPWD("qdx123456"));
        manager.setManagerName(managerName);
        manager.setMobile(mobile);
        manager.setLoginName(loginName);
        manager.setIsDisabled(0);
        manager.setSex(TKConvert.toInteger(request.getParameter("sex")));
        manager.setRemark(TKString.trim(request.getParameter("remark")));
        manager.setRoleIds(roleIds);
        manager.setPostIds(postIds);
        User user = userService.getByMobile(manager.getMobile());
        if (user != null) {
            manager.setUserId(user.getUserId());
        } else {
            manager.setUserId(userService.insertByManager(manager));
        }
        return toAjax(managerService.insert(manager));
    }

    /**
     * 修改保存用户
     */
    @Log(title = "修改管理员", businessType = BusinessType.UPDATE)
    @Permissions("manager:edit")
    @PostMapping("/edit.json")
    @ResponseBody
    public AjaxResult editSave(HttpServletRequest request) {
        int managerId = TKConvert.toInteger(request.getParameter("managerId"));
        if (managerId < 1) return error("缺少用户id");
        String managerName = TKString.trim(request.getParameter("managerName"));
        if (TKString.isEmpty(managerName)) return error("请输入用户名");
        Integer[] roleIds = TKConvert.toIntArray(request.getParameter("roleIds"));
        if (roleIds.length < 1) return error("请选择角色");
        Integer[] postIds = TKConvert.toIntArray(request.getParameter("postIds"));
        if (postIds.length < 1) return error("请选择岗位");
        Manager manager = managerService.get(managerId);
        if (manager == null) return error("找不到指定用户");
        manager.setUpdateBy(SessionUtils.getLoginName());
        manager.setManagerName(managerName);
        manager.setIsDisabled(TKConvert.toInteger(request.getParameter("isDisabled")) >= 1 ? 1 : 0);
        manager.setSex(TKConvert.toInteger(request.getParameter("sex")));
        manager.setRemark(TKString.trim(request.getParameter("remark")));
        manager.setRoleIds(roleIds);
        manager.setPostIds(postIds);
        if (manager.getUserId() == 0) {
            User user = userService.getByMobile(manager.getMobile());
            if (user != null) {
                manager.setUserId(user.getUserId());
            }
            else{
                manager.setUserId(userService.insertByManager(manager));
            }
        }
        return toAjax(managerService.updateWithAuth(manager));
    }

    @GetMapping("/resetPwd.html")
    public String resetPwd(ModelMap mmap) {
        Manager manager = SessionUtils.getManager();
        if (manager == null) return error404;
        mmap.put("manager", manager);
        return "manager/reset-pwd";
    }

    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd.json")
    @ResponseBody
    public AjaxResult resetPwdSave(HttpServletRequest request) {
        String password = request.getParameter("password");
        String loginPwd = request.getParameter("loginPwd");
        if (TKString.isEmpty(loginPwd) || loginPwd.length() < 5) return error("请输入至少6位数密码");
        Manager manager = SessionUtils.getManager();
        if (manager == null) return error("找不到指定用户");
        if (!manager.getLoginPwd().equals(TKConvert.toPWD(password))) {
            return AjaxResult.error("旧密码错误！");
        }
        manager.setLoginPwd(TKConvert.toPWD(loginPwd));
        int row = managerService.resetManagerPwd(manager);
        if (row > 0) {
           SessionUtils.setManager(manager);
        }
        return toAjax(row);
    }

    @Log(title = "删除管理员", businessType = BusinessType.DELETE)
    @Permissions("manager:remove")
    @PostMapping("/remove.json")
    @ResponseBody
    public AjaxResult remove(HttpServletRequest request, String ids) {
        int id = TKConvert.toInteger(request.getParameter("ids"));
        if (id < 1) return error("参数异常");
        return toAjax(managerService.delete(id));
    }
}